package com.jl15988.simpletools.appcore.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jl15988.simpletools.appcore.dto.AppDTO;
import com.jl15988.simpletools.appcore.dto.AppQueryDTO;
import com.jl15988.simpletools.appcore.dto.AppRequestDTO;
import com.jl15988.simpletools.appcore.service.AppService;
import com.jl15988.simpletools.common.annotation.Log;
import com.jl15988.simpletools.common.constant.OperationType;
import com.jl15988.simpletools.common.utils.Result;
import com.jl15988.simpletools.common.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 应用控制器
 *
 * @author jl15988
 */
@RestController
@RequestMapping("/api/v1/apps")
public class AppController {

    @Autowired
    private AppService appService;

    /**
     * 分页查询应用列表
     *
     * @param query 查询条件
     * @return 分页结果
     */
    @GetMapping
    public Result<IPage<AppDTO>> getAppPage(AppQueryDTO query) {
        return Result.success(appService.getAppPage(query));
    }

    /**
     * 获取应用详情
     *
     * @param id 应用ID
     * @return 应用详情
     */
    @GetMapping("/{id}")
    public Result<AppDTO> getAppDetail(@PathVariable Long id) {
        return Result.success(appService.getAppDetail(id));
    }

    /**
     * 创建应用
     *
     * @param request 应用请求DTO
     * @param icon 应用图标
     * @param appPackage 应用包文件
     * @param screenshots 应用截图
     * @param httpServletRequest HTTP请求
     * @return 应用ID
     */
    @PostMapping
    @PreAuthorize("hasAnyRole('DEVELOPER', 'ADMIN')")
    @Log(title = "创建应用", operationType = OperationType.CREATE)
    public Result<Long> createApp(@Valid AppRequestDTO request,
                                 @RequestParam("icon") MultipartFile icon,
                                 @RequestParam("package") MultipartFile appPackage,
                                 @RequestParam(value = "screenshots", required = false) MultipartFile[] screenshots,
                                 HttpServletRequest httpServletRequest) {
        Long userId = TokenUtils.getUserId(httpServletRequest);
        String username = TokenUtils.getUsername(httpServletRequest);
        return Result.success(appService.createApp(request, icon, appPackage, screenshots, userId, username));
    }

    /**
     * 更新应用
     *
     * @param request 应用请求DTO
     * @param icon 应用图标
     * @param appPackage 应用包文件
     * @param screenshots 应用截图
     * @param httpServletRequest HTTP请求
     * @return 是否成功
     */
    @PutMapping
    @PreAuthorize("hasAnyRole('DEVELOPER', 'ADMIN')")
    @Log(title = "更新应用", operationType = OperationType.UPDATE)
    public Result<Boolean> updateApp(@Valid AppRequestDTO request,
                                   @RequestParam(value = "icon", required = false) MultipartFile icon,
                                   @RequestParam(value = "package", required = false) MultipartFile appPackage,
                                   @RequestParam(value = "screenshots", required = false) MultipartFile[] screenshots,
                                   HttpServletRequest httpServletRequest) {
        Long userId = TokenUtils.getUserId(httpServletRequest);
        return Result.success(appService.updateApp(request, icon, appPackage, screenshots, userId));
    }

    /**
     * 删除应用
     *
     * @param id 应用ID
     * @param httpServletRequest HTTP请求
     * @return 是否成功
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAnyRole('DEVELOPER', 'ADMIN')")
    @Log(title = "删除应用", operationType = OperationType.DELETE)
    public Result<Boolean> deleteApp(@PathVariable Long id, HttpServletRequest httpServletRequest) {
        Long userId = TokenUtils.getUserId(httpServletRequest);
        return Result.success(appService.deleteApp(id, userId));
    }

    /**
     * 更新应用状态
     *
     * @param id 应用ID
     * @param status 状态
     * @return 是否成功
     */
    @PutMapping("/{id}/status")
    @PreAuthorize("hasRole('ADMIN')")
    @Log(title = "更新应用状态", operationType = OperationType.UPDATE)
    public Result<Boolean> updateAppStatus(@PathVariable Long id, @RequestParam Integer status) {
        return Result.success(appService.updateAppStatus(id, status));
    }

//    /**
//     * 下载应用
//     *
//     * @param id 应用ID
//     * @param httpServletRequest HTTP请求
//     * @return 应用包路径
//     */
//    @GetMapping("/{id}/download")
//    @Log(title = "下载应用", operationType = OperationType.DOWNLOAD)
//    public Result<String> downloadApp(@PathVariable Long id, HttpServletRequest httpServletRequest) {
//        // 尝试获取用户ID，未登录用户为null
//        Long userId = null;
//        try {
//            userId = TokenUtils.getUserId(httpServletRequest);
//        } catch (Exception e) {
//            // 忽略异常，表示未登录用户
//        }
//        return Result.success(appService.downloadApp(id, userId, httpServletRequest));
//    }
    
    /**
     * 提交应用审核
     *
     * @param id 应用ID
     * @param httpServletRequest HTTP请求
     * @return 是否成功
     */
    @PostMapping("/{id}/submit")
    @PreAuthorize("hasAnyRole('DEVELOPER', 'ADMIN')")
    @Log(title = "提交应用审核", operationType = OperationType.UPDATE)
    public Result<Boolean> submitToAudit(@PathVariable Long id, HttpServletRequest httpServletRequest) {
        Long userId = TokenUtils.getUserId(httpServletRequest);
        return Result.success(appService.submitToAudit(id, userId));
    }
}